<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>webSocketClient</title>
</head>
<body>
<table>
    <tr>
        <td>
            <p>协议:&nbsp;<input type="radio" name="protocol" value="ws" checked="true"/>ws<input type="radio" name="protocol" value="wss"/>wss</p>
            <p>主机:&nbsp;<input type="text" id="ip" value="127.0.0.1"/></p>
            <p>端口:&nbsp;<input type="text" id="port" value="7000"/>&nbsp;可以为空</p>
            <p>数据:&nbsp;<input type="text" id="data" value="test"/></p>
            <p><input type="button" value="打开连接" onclick="theOpen()"/></p>
            <p><input type="button" value="发送输入数据" onclick="theInputData()"/></p>
            <p><input type="button" value="发送随机数据" onclick="theRandData()"/></p>
            <p><input type="button" value="清空日志" onclick="theClear()"/></p>
        </td>
    </tr>
</table>
<p id="show"></p>
<script type="text/javascript">
var $$ = function(id){
    return document.getElementById(id);
};
var client = '';
var ipElement = $$('ip');
var portElement = $$('port');
var dataElement = $$('data');
var showElement = $$('show');
/**/
function getRadioValueByName(name){
    var list = document.getElementsByName(name);
    for(var i=0;i<list.length;i++){
        if(list[i].checked){
            return list[i].value;
            break;
        }
    }
    return '';
}
/**/
function theOpen(){
    if(client == ''){
        if(portElement.value == ''){
            var webSocketUrl = getRadioValueByName('protocol') + '://' + ipElement.value;
        }
        else{
            var webSocketUrl = getRadioValueByName('protocol') + '://' + ipElement.value + ':' + portElement.value;
        }
        console.log(webSocketUrl);
        client = new WebSocket(webSocketUrl);
        client.onopen = function(){
            onOpenHandle();
        };
        client.onmessage = function(event){
            onMessageHandle(event);
        };
        client.onclose = function(event){
            onCloseHandle();
        };
    }
    else{
        showMessage('has opened');
    }
}
function theInputData(){
    client.send(dataElement.value);
}
function theRandData(){
    client.send(Math.random());
}
function theClear(){
    showElement.innerHTML = '';
}
/**/
function onOpenHandle(){
    showMessage('open');
}
function onMessageHandle(event){
    showMessage('receive:' + event.data);
}
function onCloseHandle(){
    showMessage('close');
    client = '';
}
/**/
function showMessage(msg){
    var html = showElement.innerHTML;
    showElement.innerHTML = html + "<br>" + msg;
}
</script>
</body>
</html>
